iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 16
0
自我挑戰組

用LeetCode來訓練大腦的邏輯思維系列 第 24

LeetCode 344. Reverse String

  • 分享至 

  • xImage
  •  

題目

Write a function that reverses a string. The input string is given as an array of characters char[].

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

You may assume all the characters consist of printable ascii characters.

題意

反轉字串,空間複雜度為 O(1),使用reverse()即可解決,但這會失去解題的意義。
另一個解法,找出第一個與最後一個的值互換,第二個與倒數第二個互換,以此類推...。

Example 1:

Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Example 2:

Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

Solution

var reverseString = function (s) {
  let maxLen = s.length;
  let len = Math.floor(maxLen / 2);
  for (let i = 0; i < len; i++) {
    let tmp = s[i];
    s[i] = s[maxLen - 1 - i];
    s[maxLen - 1 - i] = tmp;
  }
  return s;
};

上一篇
LeetCode 290. Word Pattern
下一篇
LeetCode 367. Valid Perfect Square
系列文
用LeetCode來訓練大腦的邏輯思維30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言